<script setup lang="ts">
import type { CalendarList, DateList } from './components/interface';

import { computed, onMounted, ref } from 'vue';

import dayjs, { Dayjs } from 'dayjs';

import { getRoomTypePriceList } from '#/api';
import { useRoomList } from '#/hooks/useRoomList';

import CalendarHead from './components/CalendarHead.vue';
import CalendarMain from './components/CalendarMain.vue';
import EditPrice from './components/EditPrice.vue';
import EditRoom from './components/EditRoom.vue';

const { roomList, fetchRoomList } = useRoomList();

interface HeadFormType {
  selectDate: [Dayjs, Dayjs];
  dateStr: string[];
  showPrice: boolean;
  showRoomInfo: boolean;
}
// 头部筛选
const headForm = ref<HeadFormType>({
  selectDate: [dayjs().startOf('day'), dayjs().add(13, 'day').endOf('day')], // 日期范围
  dateStr: [
    dayjs().startOf('day').format('YYYY-MM-DD'),
    dayjs().add(13, 'day').endOf('day').format('YYYY-MM-DD'),
  ], // 日期范围字符串形式
  showPrice: true, // 是否显示房价
  showRoomInfo: true, // 是否显示房量房态
});

// 被选中需要展示的房型列表
const selectRoom = ref<any>([]);
const selectRoomIds = computed(() => {
  return selectRoom.value?.map((item: any) => item.id) || [];
});

// 设置房态弹窗
const openEditRoom = ref<boolean>(false);
// 设置房价
const openEditPrice = ref<boolean>(false);

// 日历列表数据
const calendarList = ref<CalendarList[]>([]);

// 是否加载中状态
const isLoading = ref(true);

// 头部多选事件
const handleCheckbox = (e: any, key: keyof HeadFormType) => {
  headForm.value[key] = e;
};
// 房型房价查询
const getRoomInfo = async () => {
  try {
    const { data } = await getRoomTypePriceList({
      endTime: headForm.value.dateStr[1] || '',
      roomTypeId: selectRoomIds.value || [],
      startTime: headForm.value.dateStr[0] || '',
    });
    calendarList.value = data || [];
    isLoading.value = false;
  } catch (error) {
    isLoading.value = false;
    console.error('查询房价失败：', error);
  }
};
// 日期选择
const changleDate = async (date: any) => {
  headForm.value.selectDate = date;
  headForm.value.dateStr = date.map((item: { format: (arg0: string) => any }) =>
    item.format('YYYY-MM-DD'),
  );
  await getRoomInfo();
};

// 切换日期翻页
const changlePage = async (type: string) => {
  if (type === 'add') {
    const startDate =
      headForm.value.selectDate[1].add(1, 'day').startOf('day') ||
      dayjs().startOf('day');
    headForm.value.selectDate = [
      startDate,
      dayjs(startDate).add(13, 'day').endOf('day'),
    ]; // 日期范围
  } else {
    const tenDaysAgo = dayjs().subtract(14, 'day').startOf('day');
    const startDate =
      headForm.value.selectDate[0].add(-1, 'day').startOf('day') ||
      dayjs().startOf('day');
    // 计算新的日期范围起始日期
    let newStartDate = dayjs(startDate).add(-14, 'day').endOf('day');

    // 判断新的起始日期是否早于十天前，若早于则重置为十天前
    if (newStartDate.isBefore(tenDaysAgo)) {
      newStartDate = tenDaysAgo;
      headForm.value.selectDate = [newStartDate, startDate];
    } else {
      headForm.value.selectDate = [
        newStartDate,
        newStartDate.add(14, 'day').endOf('day'),
      ];
    }
  }
  // 更新日期范围字符串形式
  headForm.value.dateStr = headForm.value.selectDate.map((item) =>
    item.format('YYYY-MM-DD'),
  );
  await getRoomInfo();
};

// 点击需要操作的日期房型数据
const roomDateData = ref<DateList>();

// 打开房量设置弹窗
const roomSet = (data: DateList) => {
  roomDateData.value = data;
  openEditRoom.value = true;
};

// 打开房价设置弹窗
const priceSet = (data: DateList) => {
  roomDateData.value = data;
  openEditPrice.value = true;
};

// 选择房型事件
const handleSelectRoom = async (room: string[]) => {
  selectRoom.value = roomList.value?.filter((item: any) =>
    room.includes(item.id),
  );
  await getRoomInfo();
};

onMounted(async () => {
  await fetchRoomList({
    enableStatus: true,
    name: '',
  });
  selectRoom.value = roomList.value || [];
  await getRoomInfo();
});
</script>

<template>
  <div
    class="absolute bottom-0 right-0 flex h-[100%] w-[100%] flex-col overflow-hidden"
  >
    <div
      class="card-box flex h-full w-full flex-col rounded-none border-none pb-4"
    >
      <!-- 头部筛选模块 -->
      <CalendarHead
        :form-data="headForm"
        :room-list="roomList"
        @changle-date="changleDate"
        @checkbox="handleCheckbox"
        @select-room="handleSelectRoom"
      />
      <!-- 日历模块 -->
      <CalendarMain
        :form-data="headForm"
        :list="calendarList"
        :loading="isLoading"
        :room-list="selectRoom"
        @changle-page="changlePage"
        @price-set="priceSet"
        @room-set="roomSet"
        @up-list="getRoomInfo"
      />
    </div>
    <!-- 弹窗 -->
    <EditRoom
      v-model:show="openEditRoom"
      :data="roomDateData"
      @up-list="getRoomInfo"
    />
    <!-- 房价弹窗设置 -->
    <EditPrice
      v-model:show="openEditPrice"
      :data="roomDateData"
      @up-list="getRoomInfo"
    />
  </div>
</template>

<style scoped lang="scss"></style>
